package com.oocl.admin_platform.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.oocl.admin_platform.pojo.Manager;
import com.oocl.admin_platform.service.ManagerService;
import com.oocl.admin_platform.service.factory.ServiceFactory;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static Logger logger = Logger.getLogger(LoginServlet.class);
	private ManagerService manService;

	@Override
	public void init() throws ServletException {
		manService = ServiceFactory.getManagerServiceInstance();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String uname = request.getParameter("uname");
		String password = request.getParameter("password");
		boolean isError=false;
		if (uname==null||"".equals(uname.trim())) {
			request.setAttribute("error", 1);
			isError=true;
		}
		else if (password==null||"".equals(password.trim())) {
			request.setAttribute("error", 2);
			isError=true;
		}
		else{
			Manager manager=manService.validatePasswordAndReturnManager(uname, password);
			if (manager != null) {
					request.getSession().setAttribute("manager", manager);
					logger.info("admin" + manager.getUname() + "login success");
					response.sendRedirect("sec/getMerchantList?action=all");
			} else {
				request.setAttribute("error", 3);
				isError=true;
				
			}
		}
		if (isError) {
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
		

	}

}
